<template>
  <view class="login-container">
    <view class="login-card">
      <view class="logo-section">
        <view class="logo-placeholder">🏡</view>
        <text class="app-name">村务通</text>
        <text class="app-desc">美丽乡村，和谐发展</text>
      </view>
      
      <view class="login-section">
        <!-- 未登录时显示登录区域 -->
        <template v-if="!showProfileEdit">
          <view class="login-title">欢迎使用</view>
          <view class="login-subtitle">请使用微信授权登录</view>
          
          <button 
            class="wechat-login-btn" 
            @click="handleWechatLogin"
            :loading="isLoading"
            :disabled="isLoading || !hasAgreed"
          >
            <text class="wechat-icon">💬</text>
            <text class="btn-text">{{ getButtonText() }}</text>
          </button>
        </template>
        
        <!-- 登录后显示头像昵称填写区域 -->
        <view v-if="showProfileEdit" class="profile-edit-section">
          <view class="profile-edit-title">登录成功</view>
          <view class="profile-edit-subtitle">请完善您的头像和昵称信息</view>
          <view class="profile-edit-content">
            <!-- 头像选择 -->
            <view class="avatar-section">
              <text class="label-text">头像：</text>
              <button 
                class="avatar-button" 
                open-type="chooseAvatar"
                @chooseavatar="onChooseAvatar"
              >
                <image 
                  class="avatar-preview" 
                  :src="avatarUrl || '/static/default-avatar.png'"
                  mode="aspectFill"
                ></image>
                <text class="avatar-tip">点击选择头像</text>
              </button>
            </view>
            
            <!-- 昵称输入 -->
            <view class="nickname-section">
              <text class="label-text">昵称：</text>
              <input 
                class="nickname-input"
                type="nickname"
                v-model="nickname"
                placeholder="请输入昵称"
                @blur="onNicknameChange"
              />
            </view>
            
            <!-- 保存按钮 -->
            <button 
              class="save-profile-btn"
              @click="handleSaveProfile"
              :loading="isSaving"
              :disabled="isSaving || !avatarUrl || !nickname"
            >
              保存信息
            </button>
          </view>
        </view>
        
        <!-- 未登录时显示协议勾选 -->
        <view v-if="!showProfileEdit" class="privacy-agreement">
          <checkbox-group @change="onAgreementChange">
            <label class="agreement-checkbox">
              <checkbox value="agree" :checked="hasAgreed" />
              <view class="agreement-text">
                <text class="tips-text">我已阅读并同意</text>
                <text class="link-text" @click.stop="showPrivacy('用户协议')">《用户协议》</text>
                <text class="tips-text">和</text>
                <text class="link-text" @click.stop="showPrivacy('隐私政策')">《隐私政策》</text>
              </view>
            </label>
          </checkbox-group>
        </view>
      </view>
    </view>
    
    <view class="footer">
      <text class="footer-text">让乡村更美好</text>
    </view>
  </view>
</template>

<script>
import authService from '@/utils/auth.js'
import { uploadApi } from '@/utils/api-simple.js'
import { config } from '@/config/api.js'

export default {
  data() {
    return {
      isLoading: false,
      hasAgreed: false,  // 用户必须主动勾选同意
      targetPage: null,  // 登录成功后要跳转的目标页面
      showProfileEdit: false,  // 是否显示头像昵称填写区域
      avatarUrl: '',  // 选择的头像URL
      nickname: '',  // 输入的昵称
      isSaving: false,  // 是否正在保存
      avatarUploading: false
    }
  },
  
  onLoad(options) {
    console.log('登录页面加载', options)
    // 保存来源页面信息，用于登录成功后跳转
    if (options.from) {
      this.targetPage = options.from
    }
    // 检查是否已经登录
    if (authService.isLoggedIn()) {
      console.log('用户已登录，跳转到目标页面')
      this.navigateAfterLogin()
    }
    // 不再使用自动登录，用户必须每次明确同意协议
  },
  
  methods: {
    
    async handleWechatLogin() {
      if (this.isLoading) return
      
      // 必须明确同意协议才能登录
      if (!this.hasAgreed) {
        uni.showToast({
          title: '请先勾选同意协议',
          icon: 'none',
          duration: 2000
        })
        return
      }
      
      this.isLoading = true
      
      try {
        console.log('开始微信授权登录')
        await authService.wechatLogin()
        
        uni.showToast({
          title: '登录成功',
          icon: 'success',
          duration: 1500
        })
        
        // 检查用户信息是否完整
        // 如果用户已经设置过微信头像和昵称，直接跳转；否则显示完善信息页面
        const userInfo = authService.getUserInfo()
        
        // 调试日志：查看后端返回的实际值
        console.log('登录返回的用户信息:', userInfo)
        console.log('wechatAvatar:', userInfo?.wechatAvatar)
        console.log('wechatNickname:', userInfo?.wechatNickname)
        
        // 安全获取字段值（处理 null、undefined、空字符串等情况）
        const wechatAvatar = (userInfo?.wechatAvatar && typeof userInfo.wechatAvatar === 'string') 
          ? userInfo.wechatAvatar.trim() 
          : ''
        const wechatNickname = (userInfo?.wechatNickname && typeof userInfo.wechatNickname === 'string') 
          ? userInfo.wechatNickname.trim() 
          : ''
        
        // 判断：如果两个字段都存在且不为空，说明已经设置过了
        const hasCompleteInfo = wechatAvatar !== '' && wechatNickname !== ''
        const needCompleteInfo = !hasCompleteInfo
        
        console.log('头像:', wechatAvatar, '昵称:', wechatNickname, '信息完整:', hasCompleteInfo)
        
        if (needCompleteInfo) {
          // 用户信息不完整，显示头像昵称填写区域并尝试预填
          await this.prefillProfileInfo(userInfo)
          this.showProfileEdit = true
          // 不自动跳转，让用户先完善信息
        } else {
          // 用户信息完整，直接跳转（不需要延迟，因为已经是第二次登录了）
          this.navigateAfterLogin()
        }
        
      } catch (error) {
        console.error('微信登录失败:', error)
        uni.showToast({
          title: '登录失败，请重试',
          icon: 'none',
          duration: 2000
        })
      } finally {
        this.isLoading = false
      }
    },
    
    // 预填头像和昵称，尽量减少用户操作
    async prefillProfileInfo(userInfo = {}) {
      const wechatCache = authService.getWechatUserInfo ? authService.getWechatUserInfo() : null
      
      const avatarCandidates = [
        userInfo.wechatAvatar,
        userInfo.avatar,
        userInfo.avatarUrl,
        wechatCache?.avatarUrl
      ]
      const nicknameCandidates = [
        userInfo.wechatNickname,
        userInfo.nickname,
        userInfo.nickName,
        userInfo.name,
        wechatCache?.nickName
      ]
      
      let resolvedAvatar = avatarCandidates.find(item => typeof item === 'string' && item.trim())
      let resolvedNickname = nicknameCandidates.find(item => typeof item === 'string' && item.trim())
      
      if ((!resolvedAvatar || !resolvedNickname) && this.canIUseGetUserProfile) {
        try {
          const profile = await this.requestWechatProfile()
          const wxUser = profile?.userInfo || {}
          authService.setWechatUserInfo && authService.setWechatUserInfo(wxUser)
          resolvedAvatar = resolvedAvatar || (typeof wxUser.avatarUrl === 'string' ? wxUser.avatarUrl.trim() : '')
          resolvedNickname = resolvedNickname || (typeof wxUser.nickName === 'string' ? wxUser.nickName.trim() : '')
        } catch (err) {
          console.warn('自动获取微信资料失败（可忽略）:', err)
        }
      }
      
      if (resolvedAvatar) {
        const trimmedAvatar = resolvedAvatar.trim()
        this.avatarUrl = trimmedAvatar
        if (this.isRemoteUrl(trimmedAvatar)) {
          authService.saveUserAvatar(trimmedAvatar).catch(() => {})
        }
      }
      if (resolvedNickname) {
        const trimmedNickname = resolvedNickname.trim()
        this.nickname = trimmedNickname
        authService.saveUserNickname(trimmedNickname).catch(() => {})
      }
    },
    
    requestWechatProfile() {
      return new Promise((resolve, reject) => {
        uni.getUserProfile({
          desc: '用于完善头像和昵称',
          lang: 'zh_CN',
          success: resolve,
          fail: reject
        })
      })
    },
    
    isRemoteUrl(url) {
      if (!url) return false
      const lower = url.toLowerCase()
      if (lower.startsWith('wxfile://')) return false
      if (lower.startsWith('http://tmp') || lower.startsWith('https://tmp') || lower.startsWith('//tmp')) {
        return false
      }
      return /^https?:\/\//.test(lower)
    },
    
    normalizeUploadUrl(result) {
      if (!result) return ''
      const directUrl = result.url || result.data?.url || result.data?.fileUrl
      if (directUrl) {
        return directUrl
      }
      const fileName = result.fileName || result.data?.fileName
      if (fileName) {
        if (this.isRemoteUrl(fileName)) {
          return fileName
        }
        const base = config.BASE_URL || ''
        if (!base) return fileName
        if (fileName.startsWith('/')) {
          return `${base}${fileName}`
        }
        return `${base}/${fileName}`
      }
      return ''
    },
    
    async ensureAvatarUploaded(filePath) {
      if (!filePath) return ''
      if (this.isRemoteUrl(filePath)) {
        return filePath
      }
      const result = await uploadApi.uploadImage(filePath)
      const remoteUrl = this.normalizeUploadUrl(result)
      return remoteUrl
    },
    
    // 登录成功后跳转
    navigateAfterLogin() {
      // 如果有目标页面，跳转到目标页面；否则跳转到首页
      if (this.targetPage) {
        // 跳转到目标tab页
        uni.switchTab({
          url: this.targetPage
        })
      } else {
        // 获取页面栈，如果有上一页，返回上一页；否则跳转到首页
        const pages = getCurrentPages()
        if (pages.length > 1) {
          // 有上一页，返回上一页
          uni.navigateBack()
        } else {
          // 没有上一页，跳转到首页
          this.navigateToHome()
        }
      }
    },
    
    navigateToHome() {
      // 跳转到首页（村介绍页面）
      uni.switchTab({
        url: '/pages/village-intro/village-intro'
      })
    },
    
    // 处理同意协议复选框变化
    onAgreementChange(e) {
      this.hasAgreed = e.detail.value.length > 0
      console.log('同意状态:', this.hasAgreed)
    },
    
    showPrivacy(type) {
      uni.showModal({
        title: type,
        content: `这里是${type}的完整内容。请仔细阅读用户服务协议和隐私政策，了解我们如何收集、使用和保护您的个人信息。`,
        showCancel: false,
        confirmText: '我已了解'
      })
    },
    
    // 获取按钮文本
    getButtonText() {
      if (this.isLoading) {
        return '登录中...'
      }
      if (!this.hasAgreed) {
        return '请先勾选同意协议'
      }
      return '微信授权登录'
    },
    
    // 选择头像
    async onChooseAvatar(e) {
      const tempPath = e.detail.avatarUrl
      if (!tempPath || this.avatarUploading) {
        return
      }
      
      console.log('选择头像:', tempPath)
      this.avatarUrl = tempPath
      this.avatarUploading = true
      
      try {
        const remoteUrl = await this.ensureAvatarUploaded(tempPath)
        if (!remoteUrl) {
          throw new Error('未获取到远程地址')
        }
        this.avatarUrl = remoteUrl
        await authService.saveUserAvatar(remoteUrl)
        uni.showToast({
          title: '头像已更新',
          icon: 'success',
          duration: 1500
        })
      } catch (error) {
        console.error('上传头像失败:', error)
        uni.showToast({
          title: '头像上传失败，请重试',
          icon: 'none'
        })
      } finally {
        this.avatarUploading = false
      }
    },
    
    // 昵称输入变化
    onNicknameChange(e) {
      const value = e.detail.value || e.target.value
      if (value) {
        this.nickname = value
      }
    },
    
    // 保存用户信息
    async handleSaveProfile() {
      if (!this.avatarUrl || !this.nickname || !this.nickname.trim()) {
        uni.showToast({
          title: '请完善头像和昵称',
          icon: 'none',
          duration: 2000
        })
        return
      }
      
      this.isSaving = true
      
      try {
        console.log('开始保存用户信息:', { avatar: this.avatarUrl, nickname: this.nickname })
        await authService.saveUserProfile(this.avatarUrl, this.nickname)
        
        // 保存成功后，立即更新本地显示的用户信息
        const userInfo = authService.getUserInfo()
        console.log('保存后的用户信息:', userInfo)
        
        uni.showToast({
          title: '保存成功',
          icon: 'success',
          duration: 1500
        })
        
        // 延迟跳转
        setTimeout(() => {
          this.navigateAfterLogin()
        }, 1500)
      } catch (error) {
        console.error('保存用户信息失败:', error)
        uni.showToast({
          title: '保存失败，请重试',
          icon: 'none',
          duration: 2000
        })
      } finally {
        this.isSaving = false
      }
    }
  }
}
</script>

<style scoped>
.login-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #4CAF50 0%, #45a049 100%);
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding: 40rpx;
}

.login-card {
  background-color: white;
  border-radius: 24rpx;
  padding: 60rpx 40rpx;
  width: 100%;
  max-width: 600rpx;
  box-shadow: 0 20rpx 40rpx rgba(0, 0, 0, 0.1);
}

.logo-section {
  text-align: center;
  margin-bottom: 60rpx;
}

.logo-placeholder {
  font-size: 120rpx;
  margin-bottom: 20rpx;
}

.app-name {
  display: block;
  font-size: 48rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 10rpx;
}

.app-desc {
  display: block;
  font-size: 28rpx;
  color: #666;
}

.login-section {
  text-align: center;
}

.login-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 10rpx;
}

.login-subtitle {
  font-size: 28rpx;
  color: #666;
  margin-bottom: 60rpx;
}

.wechat-login-btn {
  width: 100%;
  height: 88rpx;
  background: linear-gradient(135deg, #07C160, #06AD56);
  border-radius: 44rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 40rpx;
  border: none;
  box-shadow: 0 8rpx 20rpx rgba(7, 193, 96, 0.3);
}

.wechat-login-btn:active {
  transform: translateY(2rpx);
  box-shadow: 0 4rpx 12rpx rgba(7, 193, 96, 0.3);
}

.wechat-icon {
  font-size: 40rpx;
  margin-right: 20rpx;
}

.btn-text {
  color: white;
  font-size: 32rpx;
  font-weight: bold;
}

.privacy-agreement {
  margin-top: 20rpx;
  font-size: 24rpx;
}

.agreement-checkbox {
  display: flex;
  align-items: flex-start;
  padding: 0 10rpx;
}

.agreement-text {
  margin-left: 10rpx;
  line-height: 1.6;
}

.tips-text {
  color: #666;
}

.link-text {
  color: #4CAF50;
  text-decoration: underline;
}

/* 禁用状态的按钮样式 */
.wechat-login-btn[disabled] {
  opacity: 0.6;
  box-shadow: 0 4rpx 12rpx rgba(7, 193, 96, 0.2);
}

.footer {
  margin-top: 60rpx;
  text-align: center;
}

.footer-text {
  color: rgba(255, 255, 255, 0.8);
  font-size: 24rpx;
}

/* 头像昵称填写区域 */
.profile-edit-section {
  /* 移除上边距和边框，因为这是独立显示的区域 */
  margin-top: 0;
  padding-top: 0;
  border-top: none;
}

.profile-edit-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
  text-align: center;
  margin-bottom: 10rpx;
}

.profile-edit-subtitle {
  font-size: 28rpx;
  color: #666;
  text-align: center;
  margin-bottom: 40rpx;
}

.profile-edit-content {
  display: flex;
  flex-direction: column;
  gap: 30rpx;
}

.avatar-section,
.nickname-section {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

.label-text {
  font-size: 28rpx;
  color: #666;
  font-weight: 500;
}

.avatar-button {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background: transparent;
  border: 2rpx dashed #ddd;
  border-radius: 12rpx;
  padding: 30rpx;
  width: 100%;
}

.avatar-preview {
  width: 120rpx;
  height: 120rpx;
  border-radius: 50%;
  margin-bottom: 20rpx;
  background-color: #f5f5f5;
}

.avatar-tip {
  font-size: 24rpx;
  color: #999;
}

.nickname-input {
  width: 100%;
  height: 80rpx;
  padding: 0 20rpx;
  border: 1rpx solid #ddd;
  border-radius: 8rpx;
  font-size: 28rpx;
  color: #333;
  background-color: #fff;
}

.nickname-input:focus {
  border-color: #4CAF50;
}

.save-profile-btn {
  width: 100%;
  height: 88rpx;
  background: linear-gradient(135deg, #4CAF50, #45a049);
  border-radius: 44rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 32rpx;
  font-weight: bold;
  border: none;
  margin-top: 20rpx;
  box-shadow: 0 8rpx 20rpx rgba(76, 175, 80, 0.3);
}

.save-profile-btn:active {
  transform: translateY(2rpx);
  box-shadow: 0 4rpx 12rpx rgba(76, 175, 80, 0.3);
}

.save-profile-btn[disabled] {
  opacity: 0.6;
  box-shadow: 0 4rpx 12rpx rgba(76, 175, 80, 0.2);
}
</style>
